package com.atguigu.daijia.common.login;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.condition.RequestConditionHolder;

@Slf4j
@Component
@Aspect     //表示本类是切面类
public class GuiguLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    //用环绕通知进行判断
    //内部加上切入点表达式（对哪些规则的类进行增强）
    @Around("execution(* com.atguigu.daijia.*.controller.*.*(..)) && @annotation(guiguLogin)")
    public Object login(ProceedingJoinPoint proceedingJoinPoint,GuiguLogin guiguLogin) throws Throwable{
        //1.获取request对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) attributes;
        HttpServletRequest request = sra.getRequest();
        //2.从请求头中获取token
        String token = request.getHeader("token");
        //3.判断token是否为空，如果为空，放回登录提示
        if(StringUtils.isEmpty(token)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        //4.token不为空，查询redis
        String customerId = (String) redisTemplate.opsForValue()
                .get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        //5.查redis对应的用户Id，把用户Id放置到ThreadLocal中，方便后续取值
        if(StringUtils.hasText(customerId)){
            AuthContextHolder.setUserId(Long.valueOf(customerId));
        }
        //6.执行增强的业务方法
        return proceedingJoinPoint.proceed();
    }
}
